<template>
  <!-- 教师基本资料修改组件 -->
  <div>
    <!-- 表单 -->
    <el-form
      ref="form"
      :rules="rules"
      :model="form"
      label-position="right"
      label-width="150px"
    >
      <!-- 姓名 -->
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="form.name"
          style="width: 300px"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <!-- 上传照片 -->
      <el-form-item label="上传照片">
        <el-upload
          action="#lsj"
          :auto-upload="false"
          list-type="picture-card"
          :on-change="handleImageChange"
          :on-remove="handleImageRemove"
          :limit="1"
          :file-list="fileList"
          class="my-upload"
        >
          <el-button
            v-if="!form.personal_photo || selectedFile"
            slot="trigger"
            size="small"
            type="primary"
          >选取文件
          </el-button
          >
          <img
            v-if="form.personal_photo && !selectedFile"
            slot="trigger"
            :src="form.personal_photo"
            style="width: 200px; height: 200px"
          />
          <div slot="tip" class="el-upload__tip">最佳头像尺寸:270x290(px)</div>
        </el-upload>
      </el-form-item>
      <!-- 性别 -->
      <el-form-item label="性别">
        <el-radio-group v-model="form.sex">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 所在系 -->
      <el-form-item label="所在系" prop="department">
        <el-select v-model="form.department">
          <el-option
            v-for="item in departments"
            :key="item.department_id"
            :label="item.department_name"
            :value="item.department_name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 研究方向 -->
      <el-form-item label="研究方向">
        <el-input
          v-model="form.research_direction"
          type="textarea"
          autosize
        ></el-input>
      </el-form-item>
      <!-- 办公室 -->
      <el-form-item label="办公室">
        <el-input v-model="form.office" style="width: 300px"></el-input>
      </el-form-item>
      <!-- 办公电话 -->
      <el-form-item label="办公电话">
        <el-input v-model="form.phone" style="width: 300px"></el-input>
      </el-form-item>
      <!-- 电子邮件 -->
      <el-form-item label="电子邮件" >
        <el-input
          type="email"
          v-model="form.email"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <!-- 个人主页 -->
      <el-form-item label="个人主页">
        <el-input v-model="form.personal_page" style="width: 300px"></el-input>
      </el-form-item>
      <!-- 个人简介 -->
      <el-form-item label="个人简介">
        <TinymceEditor v-model="form.personal_profile"></TinymceEditor>
      </el-form-item>
      <!--教育经历-->
      <el-form-item label="教育经历">
        <TinymceEditor v-model="form.education_experience"></TinymceEditor>
      </el-form-item>
      <!--工作经历-->
      <el-form-item label="工作经历">
        <TinymceEditor v-model="form.work_experience"></TinymceEditor>
      </el-form-item>
      <!--科研成果-->
      <el-form-item label="科研成果">
        <TinymceEditor v-model="form.scientific_payoffs"></TinymceEditor>
      </el-form-item>
      <!--教学成果-->
      <el-form-item label="教学成果">
        <TinymceEditor v-model="form.teaching_result"></TinymceEditor>
      </el-form-item>
      <!-- 职称 -->
      <el-form-item label="职称">
        <el-select v-model="form.title_name">
          <el-option
            v-for="item in titles"
            :key="item.title_id"
            :label="item.title_name"
            :value="item.title_name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import service from '@/utils/service';
import TinymceEditor from '@/components/Tinymce';

export default {
  components: {
    TinymceEditor,

  },
  data() {
    return {
      form: {},
      //所在系
      departments: [
      ],
      //职称
      titles: [],
      //验证规则
      rules: {
        name: [{required: true, message: "请输入姓名", trigger: "blur"}],
        // email: [
        //   {required: true, message: "请输入邮箱地址", trigger: "blur"},
        //   {
        //     type: "email",
        //     message: "请输入正确的邮箱地址",
        //     trigger: "blur,change",
        //   },
        // ],
        gender: [{required: true, message: "请选择性别", trigger: "blur"}],
        department: [
          {required: true, message: "请选择所在系", trigger: "blur"},
        ],
      },
      selectedFile: "",
      fileList:[],
    };
  },
  methods: {
    //获取所有的教师职称
    async getAllTitles() {
      try {
        const apiUrl = "/teachers/title";
        const response = await service.get(apiUrl);
        if (response.data.code === 20041) {
          this.titles = response.data.data;
        }
      } catch {
        console.log("获取所有职称出错");
      }
    },
    //上传组件选择图片后触发的方法
    handleImageChange(file) {
      if(file&&file.size <= 100*1024*1024){
        this.selectedFile = file;
        console.log(this.fileList);
      }else {
        this.$message.error('图片大小不能超过100MB');
        this.fileList = [];

      }

    },
    //移出图片时触发的方法
    handleImageRemove(file) {
      this.selectedFile = "";
    },

    //根据token获取教师基本信息
    async getTeacherBaseInfo() {
      try {
        const apiUrl =
          "/teachers/getInfo";
        const response = await service.get(apiUrl, {
          headers: {
            Authorization: this.$store.state.token,
          },
        });

        if (response.data.code === 20041) {
          this.form = response.data.data;
        }
      } catch {
        console.log("根据Token获取教师基本信息出错");
      }
    },
    //获取所有的系别
    async getAllDepartments(){
      try{
        const relativeUrl = "/departs/get";
        const response = await service.get(relativeUrl,{
          headers: {
            Authorization: this.$store.state.token,
          },});
        if(response.data.code === 20041){
          this.departments = response.data.data;
        }
      }catch{
        console.log('获取所有系别出错');
      }
    },
    handleSave() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            // JSON.stringify 将JavaScript对象转换为字符串
            const formJson = JSON.stringify(this.form);
            console.log('form', this.form);

            const apiUrl = "/teachers/update";
            let formData = new FormData();

            const blob = new Blob([formJson], {type : 'application/json;charset=utf-8'});
            formData.append('te', blob);

            // 将文件添加到表单对象中
            formData.append('selectedFile', this.selectedFile.raw);

            const response = await service.put(apiUrl, formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': this.$store.state.token
              }
            });

            if (response.data.code === 20031) {
              this.$message.success("修改成功");
            } else {
              throw new Error('修改失败，提交数据出错');
            }
          } catch {
            console.log("修改教师基本资料出错");
          }
        }
      });
    },
  },
  created() {
    this.getAllDepartments();
    this.getAllTitles();
    this.getTeacherBaseInfo();
  },
};
</script>

<style scoped>
.my-upload >>> .el-upload-list--picture-card .el-upload-list__item {
  width: 200px;
  height: 200px;
}

.my-upload >>> .el-upload--picture-card {
  width: 200px;
  height: 200px;
}

.my-upload >>> .el-button--small {
  padding-top: 10px;
}

.el-upload__tip {
  color: red;
}
</style>
